import axios from "axios"
import { getToken } from "./auth"
import { store } from "@/store"
import history from "./history"
import { logoutAsync } from "@/store/slice/userinfo.slice"
// 创建一个新的axios实例
const service = axios.create({
  baseURL: "https://toutiao.itheima.net/v1_0", // 设置基础地址
  timeout: 5000,
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (getToken()) {
      // 如果有token 注入token
      config.headers.Authorization = `Bearer ${getToken()}`
      // config.headers = { Authorization: `Bearer ${getToken()}` } // 这么写有问题
    }
    return config // 这里一定要return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // response 默认加了一层data数据
    return response?.data?.data || response
  },
  (error) => {
    if (error?.response?.status === 401) {
      // 认为token超时-清除token
      // dispatch - 清除的action
      store.dispatch(logoutAsync()) // 清除token
      // 跳转到登录页
      history.replace("/login") //跳转到登录页
    }
    return Promise.reject(error)
  }
)

export default service
